package com.generator.code.controller;

import com.generator.code.mapper.MysqlMapper;
import com.generator.code.model.GenColumnEntity;
import com.generator.code.model.GenTableEntity;
import com.generator.code.model.ZipModel;
import com.generator.code.service.MySqlGeneratorService;
import com.generator.code.util.ZipUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author guoq.z
 * @date 2021/4/1
 */
@Api
@RestController
@RequestMapping("/generator")
public class GeneratorController {

    @Autowired
    private MysqlMapper mysqlMapper;
    @Autowired
    private MySqlGeneratorService mySqlGeneratorService;

    @Value("${zipFilePath}")
    private String zipFilePath;

    @Value("${zipFilePathParent}")
    private String zipFilePathParent;


    /**
     * 生成代码入口类
     * @param tableNames    表名称，多个表用英文逗号隔开，不传就生成数据库中的所有表
     */
    @ApiOperation("getGeneratorCode")
    @GetMapping("/getGeneratorCode")
    public void getGeneratorCode(String tableNames) {
        List<String> tableNameList = new ArrayList<>();
        if (StringUtils.isNotBlank(tableNames)) {
            String[] split = tableNames.split(",");
            tableNameList = Arrays.asList(split);
        }

        if (CollectionUtils.isEmpty(tableNameList)) {
            tableNameList = mysqlMapper.queryAllTableName();
        }

        List<ZipModel> zipModelList = new ArrayList<>();
        for (String tableName : tableNameList) {
            //查询表信息
            GenTableEntity table = mysqlMapper.queryTableInfo(tableName);
            //查询列信息
            List<GenColumnEntity> columns = mysqlMapper.queryColumns(tableName);
            List<ZipModel> zipModels = mySqlGeneratorService.generatorCode(table, columns);
            zipModelList.addAll(zipModels);
        }

        ZipUtils.createZipFile(zipFilePath, zipModelList);
    }

    /**
     * 生成代码入口类
     *
     * @param tableNames 表名称，多个表用英文逗号隔开，不传就生成数据库中的所有表
     */
    @ApiOperation("postGeneratorCode")
    @PostMapping("/postGeneratorCode")
    public String generatorCode(@RequestBody List<String> tableNames) {
        String join = String.join(",", tableNames);
        getGeneratorCode(join);
        openFolder(zipFilePathParent);
        return zipFilePath;
    }

    /**
     * 打开指定路径的文件夹
     * @param folderPath 文件夹路径（如：D:/downloads 或 /home/user/files）
     * @return 是否打开成功
     */
    public static boolean openFolder(String folderPath) {
        if (folderPath == null || folderPath.trim().isEmpty()) {
            return false;
        }
        try {
            String os = System.getProperty("os.name").toLowerCase();
            Process process = null;
            // 根据操作系统类型执行不同命令
            if (os.contains("win")) {
                // Windows系统：使用explorer.exe
                process = new ProcessBuilder("explorer.exe", folderPath).start();
            } else if (os.contains("mac")) {
                // Mac系统：使用open命令
                process = new ProcessBuilder("open", folderPath).start();
            } else if (os.contains("nix") || os.contains("nux") || os.contains("aix")) {
                // Linux/Unix系统：使用xdg-open命令
                process = new ProcessBuilder("xdg-open", folderPath).start();
            } else {
                // 不支持的操作系统
                return false;
            }
            // 等待命令执行完成（0表示成功）
            int exitCode = process.waitFor();
            return exitCode == 0;

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        }
    }
}
